package org.onion.pattern.kit.common.jackson.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;

/**
 * 时间反序列化-取上限值
 */
public class LocalDateTimeRoundUpDeserializer extends JsonDeserializer<LocalDateTime> {

    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        if (ObjectUtils.isEmpty(jsonParser)) {
            return null;
        }

        String txt = jsonParser.getText();

        return parse(txt);
    }

    public static LocalDateTime parse(String txt) {
        if (StringUtils.isBlank(txt)) {
            return null;
        }

        try {
            return LocalDateTime.parse(txt, LocalDateTimeDeserializer.fmt_yyyy_MM_dd_HH_mm_ss);
        } catch (Exception e) {
            //
        }

        try {
            LocalDate parse = LocalDate.parse(txt, LocalDateTimeDeserializer.fmt_yyyy_MM_dd);
            return LocalDateTime.of(parse.getYear(), parse.getMonthValue(), parse.getDayOfMonth(), 23, 59, 59);
        } catch (Exception e) {
            //
        }

        try {
            LocalDateTime parse = LocalDateTime.parse(txt, LocalDateTimeDeserializer.fmt_yyyy_MM_dd_HH_mm);
            return LocalDateTime.of(parse.getYear(), parse.getMonthValue(), parse.getDayOfMonth(), parse.getHour(), parse.getMinute(), 59);
        } catch (Exception e) {
            //
        }

        try {
            LocalDate parse = LocalDate.parse(txt + "-01", LocalDateTimeDeserializer.fmt_yyyy_MM_dd);
            LocalDateTime localDateTime = LocalDateTime.of(parse.getYear(), parse.getMonthValue(), 1, 23, 59, 59);
            localDateTime = localDateTime.with(TemporalAdjusters.lastDayOfMonth());
            return localDateTime;
        } catch (Exception e) {
            //
        }

        try {
            LocalDateTime parse = LocalDateTime.parse(txt, LocalDateTimeDeserializer.fmt_yyyy_MM_dd_HH);
            return LocalDateTime.of(parse.getYear(), parse.getMonthValue(), parse.getDayOfMonth(), parse.getHour(), 59, 59);
        } catch (Exception e) {
            throw new IllegalArgumentException(txt + " 日期反序列化失败 ");
        }
    }


}
